package com.java.advance.server;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

/**
 * Created by yangminghua on 2019/4/10.
 */
public class HelloHandler extends SimpleChannelHandler {

    /**
     * 接收消息
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

        System.out.println("messageReceived");
//        System.out.println(e.getMessage());
        //没有解码的时候采用此种方法
//        ChannelBuffer channelBuffer = (ChannelBuffer) e.getMessage();
//        String msg = new String(channelBuffer.array());
        //管道中解码之后采用此种方法
        System.out.println(e.getMessage());
        //回写数据
        //没有编码
//        ChannelBuffer copiedBuffer = ChannelBuffers.copiedBuffer("hi".getBytes());
//        ctx.getChannel().write(copiedBuffer);
        //在管道中编码之后
        ctx.getChannel().write("Hi\n");
        super.messageReceived(ctx, e);
    }

    /**
     * 捕获异常
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        System.out.println("exceptionCaught");

        super.exceptionCaught(ctx, e);
    }

    /**
     * 新链接
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelConnected");

        super.channelConnected(ctx, e);
    }

    /**
     * 必须是链接已经建立，关闭通道的时候才会触发
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelDisconnected");

        super.channelDisconnected(ctx, e);
    }

    /**
     * channel关闭的时候触发
     *
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelClosed");

        super.channelClosed(ctx, e);
    }
}
